const axios = require('axios').default;
const request_timeout = 10000;
const baseInstance = axios.create({
    // baseURL: base_url,
    timeout: request_timeout,
});

//request interceptor configuration
baseInstance.interceptors.request.use(
    function (config) {
        //if validateStatus return true, then promise status will be resove, otherwise, it will be reject.
        config.validateStatus = function (http_status) {
            return http_status >= 200;
        };

        //set header content type for each request.
        // config.headers = {
        //     'Content-Type': 'application/json'
        // };

        return config;
    },

    //handle request error
    function (error) {
        //something happened in setting up the request that triggered an Error
        //formate error response data structure
        return Promise.reject(error);
    }
);

//response interceptor configuration
baseInstance.interceptors.response.use(
    //formate success response data structure
    function (response) {
        return Promise.resolve(response.data);
    },
    //formate error response data structure
    function (error) {
        return Promise.reject(error);
    }
);

const get = (url, headers) => {
    return baseInstance({
        url: url,
        method: 'GET',
        headers: headers
    });
};
const post = (url, reqData, headers) => {
    return baseInstance({
        url: url,
        method: 'POST',
        data: reqData,
        headers: headers
    });
};
const patch = (url, reqData, headers) => {
    return baseInstance({
        url: url,
        method: 'PATCH',
        data: reqData,
        headers: headers
    });
};
const deleted = (url, headers) => {
    return baseInstance({
        url: url,
        method: 'DELETE',
        headers: headers
    });
};

module.exports = {
    get,
    post,
    patch,
    deleted
};
